package com.imooc.activitiweb.test;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 描述:
 *
 * @author yanzhengwu
 * @create 2021-08-22 21:42
 */

@SpringBootTest
@Slf4j
public class ActivitiTestTask {

    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;
    @Resource
    private IdentityService identityService;

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private ProcessEngine processEngine;

    @Resource
    private HistoryService historyService;

    @Test
    public void initUser() {

        //项目中每创建一个新用户，对应的要创建一个Activiti用户
        //两者的userId和userName一致
        User admin = identityService.newUser("2");
        admin.setLastName("admin2");
        identityService.saveUser(admin);

        //项目中每创建一个角色，对应的要创建一个Activiti用户组
        /*Group adminGroup = identityService.newGroup("1");
        adminGroup.setName("admin2");
        identityService.saveGroup(adminGroup);*/

        //用户与用户组关系绑定
        identityService.createMembership("2", "1");
    }


    @Test
    public void start() {

        System.out.println("开始流程");
        /*Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("employeeName", "Kermit");
        variables.put("numberOfDays", new Integer(4));
        variables.put("vacationMotivation", "I'm really tired!");

        //RuntimeService runtimeService = processEngine.getRuntimeService();
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("huiqian", variables);
        System.out.println(processInstance.getProcessDefinitionId());


        // Verify that we started a new process instance
        log.info("Number of process instances: " + runtimeService.createProcessInstanceQuery().count());*/


        //启动流程实例，字符串"vacation"是BPMN模型文件里process元素的id
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("shenpi");
        //流程实例启动后，流程会跳转到请假申请节点
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        //设置请假申请任务的执行人
        taskService.setAssignee(task.getId(), "2");

        //设置流程参数：请假天数和表单ID
        //流程引擎会根据请假天数days>3判断流程走向
        //formId是用来将流程数据和表单数据关联起来
        Map<String, Object> args = new HashMap<>();
        args.put("days", "3");
        args.put("formId", "123");

        //完成请假申请任务
        taskService.complete(task.getId(), args);
        log.info("完成审核申请taskid==>"+task.getId());

    }

    @Test
    public void getGroup(){
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("shenpi");
        Task task2 = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        //查出当前登录用户所在的用户组
        List<Group> groups = identityService.createGroupQuery()
                .groupMember(String.valueOf("1")).list();
        List<String> groupNames = groups.stream().map(group -> group.getName()).collect(Collectors.toList());

        //查询用户组的待审批请假流程列表
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey("shenpi")
                .taskCandidateGroupIn(groupNames)
                .listPage(0, 10);
        tasks.forEach(task -> {
            System.out.println("taskid=="+task.getId());
            System.out.println("taskName=="+task.getName());

        });
        //根据流程实例ID查询请假申请表单数据
        List<String> processInstanceIds = tasks.stream()
                .map(task -> task.getProcessInstanceId())
                .collect(Collectors.toList());

        //List<VacationApplyBasicPO> vacationApplyList = vacationRepository.getVacationApplyList(processInstanceIds);
    }


    @Test
    public void getNode(){
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("shenpi");
        Task vacationAudit = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("1").list();

        //查询当前审批节点
        //Task vacationAudit = taskService.createTaskQuery().taskId("27501").singleResult();

        if (1 == 1) {//审批通过
            //设置流程参数：审批ID
            Map<String, Object> args = new HashMap<>();
            args.put("auditId", "123");

            //设置审批任务的执行人
            taskService.claim(vacationAudit.getId(), "1");
            //完成审批任务
            taskService.complete(vacationAudit.getId(), args);
        } else {
            //审批不通过，结束流程
            runtimeService.deleteProcessInstance(vacationAudit.getProcessInstanceId(), "123");
        }

    }
    @Test
    public void startTask() {
        // Fetch all tasks for the management group
        // askService taskService = processEngine.getTaskService();
        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("management").list();
        for (Task task : tasks) {
            log.info("Task available: " + task.getName());
        }
    }

    @Test
    public void main() {


    }


    public void complete(Task task, Integer status, Map<String, String> map) {
        System.out.println("组的service");
        /**
         * 用户逻辑写在这
         */
        HashMap<String, Object> variables = new HashMap<>();
        // 分支条件判断 驳回或同意
        variables.put("status", status);
        setAssigneeOrCandidateUser(taskService, task, map.get("userId"));
        taskService.complete(task.getId(), variables);

    }

    private void setAssigneeOrCandidateUser(TaskService taskService, Task task, String userId) {
        // 设置执行人
        List<IdentityLink> identityLinksForTask = taskService.getIdentityLinksForTask(task.getId());
        for (IdentityLink i : identityLinksForTask) {
            // 判断是组任务还是个人任务
            if (null == i.getGroupId() || i.getGroupId().equals(""))
                task.setAssignee(userId);
            else
                taskService.addCandidateUser(task.getId(), userId);
        }
    }
}
